package com.uum.mq.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.uum.common.core.constant.SecurityConstants;
import com.uum.common.core.result.Result;
import com.uum.web.exception.BizException;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/websocket/{userId}/{token}")
@Component
public class WebSocketConfig {
    private static int onlineCount = 0;
    private static Map<String, WebSocketConfig> clients = new ConcurrentHashMap<>();
    private Session session;
    private String userId = "";


    @Bean(name = "serverEndpointExporter")
    public ServerEndpointExporter getServerEndpointExporterBean() {
        return new ServerEndpointExporter();
    }


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId, @PathParam("token") String token) {
        if (StrUtil.isBlank(token) || !StrUtil.startWithIgnoreCase(token, SecurityConstants.JWT_PREFIX)) {
            return;
        }
        token = token.substring(SecurityConstants.JWT_PREFIX.length());
        String ip = "172.18.0.3:10000";
        try {
            NacosServiceManager nacosServiceManager = SpringUtil.getBean(NacosServiceManager.class);
            NacosDiscoveryProperties nacosDiscoveryProperties = SpringUtil.getBean(NacosDiscoveryProperties.class);
            NamingService namingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());

            Instance instance = namingService.selectOneHealthyInstance("uum-gateway","prod");
            ip = instance.getIp() + ":" + instance.getPort();
        } catch (NacosException e) {
            e.printStackTrace();
        }
        String json = HttpUtil.get(ip +"/uum-auth/oauth/checkToken?token=" + token);
        Result result = JSONObject.parseObject(json, Result.class);
        boolean success = Result.isSuccess(result);
        if (success) {
            this.session = session;
            this.userId = userId;
            onlineCount++;
            clients.put(userId, this);
            System.out.println("连接成功,当前用户id是:[" + userId + "]当前在线人数:[" + onlineCount + "]");
        } else {
            throw new BizException(result.getMsg());
        }

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        onlineCount--;
        if (onlineCount < 0) {
            onlineCount = 0;
        }
        clients.remove(userId);
        System.out.println("有一连接关闭,当前在线人数:[" + onlineCount + "]");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
    }

    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    public static void sendMessage(Map map) {
        String msg = JSONArray.toJSONString(map);
        System.out.println(msg);
        for (WebSocketConfig item : clients.values()) {
            item.session.getAsyncRemote().sendText(msg);
        }
    }
}
